<?php


namespace App\Services;


use App\Models\Admin;
use App\Models\NewPrecut;
use Illuminate\Http\Request;
use \Exception;
use Illuminate\Support\Facades\DB;

class NewPrecutService
{
    private $userService;

    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }

    public function transfer()
    {

    }

    public function transferRecord(Request $request)
    {
        $model = DB::table('new_precut_transfer as rt')
            ->leftJoin('new_precut as rm', 'rm.id', 'rt.precut_id')
            ->leftJoin('users as y', 'y.id', 'rt.transfer_by_user_id')
            ->leftJoin('users as x', 'x.id', 'rt.transfer_to_user_id')
            ->leftJoin('users as c', 'c.id', 'rt.created_by')
            ->leftJoin('users as ys', 'ys.id', 'y.creator_id')
            ->leftJoin('users as xs', 'xs.id', 'x.creator_id')
            ->select([
                    'rt.*',
                    DB::raw('y.abbr as ygmsmc'),
                    DB::raw('x.abbr as xgmsmc'),
                    DB::raw('if(y.user_type=3, ys.abbr, y.abbr) as ysdmc'),
                    DB::raw('if(x.user_type=3, xs.abbr, x.abbr) as xsdmc'),
                    'x.user_type as xuser_type',
                    'y.user_type as yuser_type',
                    'c.abbr as czy', 'rm.precut_id',
                    ]
            );
        $model = filterByColumns($model, ['rm.precut_id', 'y.abbr', 'x.abbr', 'c.abbr' ]);
        $model = filterByDateRange($model, 'rt.created_at');
        if ($request->input('status')!==null) {
            $status = (int) $request->input('status');
            $model = $model->where('rt.approved', $status);
        }

        $user_id = session('admin.id');

        /*
         * 如果用户为管理员 */
        if (session('admin.user_type') != 1) {
            $model = $model->where(function ($query) use ($user_id) {
                $query->where('y.id', $user_id)
                    ->orWhere('y.creator_id', $user_id)
                    ->orWhere('x.id', $user_id)
                    ->orWhere('x.creator_id', $user_id);
            });
        }
        $model = $model->orderByDesc('rt.id');
        $data = $model->paginate(50);

        return $data;
    }

    public function getPrecuts(string $keyword, int $userId = 0, int $userType = 0)
    {
        $model = DB::table('new_precut')
            ->leftJoin('users', 'users.id', 'new_precut.user_id')
            ->where('precut_id', 'like', $keyword . '%')
            ->whereIn('users.user_type', [2, 3])
            ->where('new_precut.status', 0);
        if (!empty($userId) && $userType == 2) {
            $userIds = $this->userService->getDealers([$userId]);
            $userIdArr = array_merge([$userId], $userIds ?? []);
            $model = $model->whereIn('user_id', $userIdArr);
        }
        if (!empty($userId) && $userType == 3) {
            $userIdArr = $this->userService->getBelongUserIdArr($userId);
            $model = $model->whereIn('user_id', $userIdArr);
        }

        $precuts = $model->select('new_precut.*')->get();
        if (empty($precuts)) {
            return [];
        }

        return $precuts;
    }

    /**
     * 通过id和用户id获取信息
     *
     * @param int $userId
     * @return array
     */
    public function getUserById(int $userId = 0)
    {
        $user = Admin::where('id', $userId)->select('id as value', 'abbr as label', 'user_type')->get();
        if (empty($user) || !in_array($user[0]->user_type, [2, 3])) {
            return [];
        }

        return $user;
    }

    /**
     * 保存数据
     *
     * @param Request $request
     * @return mixed
     * @throws Exception
     */
    public function save(Request $request)
    {
        if (empty($request->input('precut_id'))) {
            throw new Exception('缺少套件id');
        }
        if (empty($request->input('ygmsid'))) {
            throw new Exception('缺少发起方账号');
        }

        if (empty($request->input('xsdid')) && empty($request->input('xgmsid'))) {
            throw new Exception('缺少接受方账号');
        }
        if (!empty($request->input('xsdid')) && empty($request->input('xgmsid'))) {
            $receiverUserId = $request->input('xsdid');
        } else {
            $receiverUserId = $request->input('xgmsid');
        }

        if (empty($request->input('note'))) {
            throw new Exception('缺少备注');
        }

        $precut = NewPrecut::where('precut_id', $request->input('precut_id'))->first();
        if (empty($precut)) {
            throw new Exception('该套件不存在');
        }
        if ($precut->status == 1) {
            throw new Exception('该套件已被使用，不可分配');
        }
        if ($precut->user_id != $request->input('ygmsid')) {
            throw new Exception('该套件非发起方不可调货');
        }
        if ($precut->user_id == $receiverUserId) {
            throw new Exception('该套件属于调货方不可调货');
        }

        $insertData = [
            'precut_id' => $precut->id,
            'transfer_by_user_id'   => $request->input('ygmsid'),
            'transfer_to_user_id'   => $receiverUserId,
            'note'  => trim($request->input('note') ?? ''),
            'created_at'    => date('Y-m-d H:i:s'),
            'created_by'    => session('admin.id'),
            'approved'      => session('admin.user_type') == 1 ? 1 : 0,
        ];

        if (session('admin.user_type') == 1) {
            $insertData['approved_date'] = date('Y-m-d H:i:s');
        }
        $result = DB::table('new_precut_transfer')->insert($insertData);

        if (!$result) {
            throw new Exception('调货失败');
        }

        if (session('admin.user_type') == 1) {
            NewPrecut::where('id', $precut->id)->update(['user_id' => $receiverUserId, 'updated_by' => session('admin.id') ]);
        }

        return $result;
    }
}